package com.axx.android.home.activity;

import android.content.Intent;
import android.os.Bundle;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;

import com.axx.android.LetterApp;
import com.axx.android.R;
import com.axx.android.base.BaseActivity;
import com.axx.android.common.BaseModel;
import com.axx.android.common.Constants;
import com.axx.android.common.SJRefreshView;
import com.axx.android.home.adapter.SearchAdapter;
import com.axx.android.home.model.SearchResult;
import com.axx.android.home.model.SearchWrapper;
import com.axx.android.home.model.User;
import com.axx.android.letter.activity.LetterDetailActivity;
import com.axx.android.letter.activity.RecipientActivity;
import com.axx.android.profile.auth.activity.LoginActivity;
import com.axx.android.profile.message.model.MessageLetter;
import com.axx.android.utils.GsonUtils;
import com.axx.android.utils.HttpUtils;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.loadmore.SimpleLoadMoreView;
import com.google.gson.reflect.TypeToken;

import org.json.JSONException;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import butterknife.Bind;
import butterknife.ButterKnife;
import butterknife.OnClick;

public class SearchActivity extends BaseActivity {


    @Bind(R.id.btn_back)
    Button mBtnBack;
    @Bind(R.id.btn_search)
    Button mBtnSearch;
    @Bind(R.id.layout_toolbar)
    RelativeLayout mLayoutToolbar;
    @Bind(R.id.activity_search)
    LinearLayout mActivitySearch;
    @Bind(R.id.rv_list)
    RecyclerView mRvList;
    @Bind(R.id.et_content)
    EditText mEtContent;
    @Bind(R.id.refresh_view)
    SJRefreshView mRefreshView;

    private List<SearchWrapper> list = new ArrayList<>();
    private SearchAdapter searchAdapter;

    private int curPage = 1;
    private int pageSize = 15;

    @Override
    public int getLayoutId() {
        return R.layout.activity_search;
    }

    @Override
    public void init(Bundle savedInstanceState) {
        initAdapter();
        mRefreshView.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {
                curPage = 1;
                fetchResult();
            }
        });
    }

    private void initAdapter() {
        searchAdapter = new SearchAdapter(list);
        mRvList.setLayoutManager(new LinearLayoutManager(this));
        mRvList.setAdapter(searchAdapter);

        searchAdapter.setLoadMoreView(new SimpleLoadMoreView());
        searchAdapter.setOnLoadMoreListener(new BaseQuickAdapter.RequestLoadMoreListener() {
            @Override
            public void onLoadMoreRequested() {
                curPage++;
                fetchResult();
            }
        }, mRvList);
        searchAdapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
                if (searchAdapter.getData().get(position).getItemType() == SearchWrapper.USER) {
                    String jsonString = GsonUtils.toJson(searchAdapter.getData().get(position).getUserListBean());
                    startUserActivity(jsonString);
                }
                if (searchAdapter.getData().get(position).getItemType() == SearchWrapper.LETTER) {
                    Intent intent = new Intent(SearchActivity.this, LetterDetailActivity.class);
                    intent.putExtra("id", searchAdapter.getData().get(position).getLetterListBean().getId());
                    intent.putExtra("from", "home");
                    startActivity(intent);
                }
            }
        });
//        searchAdapter.setOnItemChildClickListener(new BaseQuickAdapter.OnItemChildClickListener() {
//            @Override
//            public void onItemChildClick(BaseQuickAdapter adapter, View view, int position) {
//                if (searchAdapter.getData().get(position).getItemType() == SearchWrapper.LETTER) {
//                    String jsonString = null;
//                    switch (view.getId()) {
//                        case R.id.iv_to_header:
//                            jsonString = GsonUtils.toJson(searchAdapter.getData().get(position).getLetterListBean().getToUser());
//                            break;
//                        case R.id.iv_from_header:
//                            jsonString = GsonUtils.toJson(searchAdapter.getData().get(position).getLetterListBean().getToUser());
//                            break;
//                    }
//                    startUserActivity(jsonString);
//                }
//            }
//        });
    }

    private void startUserActivity(String jsonString) {
        try {
            User.UserListBean userListBean1 = GsonUtils.fromJson(jsonString, new TypeToken<User.UserListBean>() {
            });
            Intent intent = new Intent(SearchActivity.this, RecipientActivity.class);
            intent.putExtra("model", userListBean1);
            startActivity(intent);
        } catch (JSONException e) {
            e.printStackTrace();
        }
    }

    private void fetchResult() {
        mRefreshView.setRefreshing(true);
        HashMap<String, String> hashMap = new HashMap();
        hashMap.put("nowpage", curPage + "");
        hashMap.put("pagenum", pageSize + "");
        hashMap.put("keyword", mEtContent.getText().toString());
        if (LetterApp.curLocation != null) {
            hashMap.put("userLongitude", LetterApp.curLocation.getLongitude() + "");
            hashMap.put("userLatitude", LetterApp.curLocation.getLatitude() + "");
        }

        HttpUtils.post(Constants.Url.User.USER_SEARCH, hashMap, new HttpUtils.SJCallBack() {
            @Override
            public void onSuccess(String result) {
                mRefreshView.setRefreshing(false);
                try {
                    BaseModel<SearchResult> searchResultBaseModel = GsonUtils.fromJson(result, new TypeToken<BaseModel<SearchResult>>() {
                    });
                    if (searchResultBaseModel.isSuccess()) {
                        showSuccess(groupData(searchResultBaseModel.data));
                    } else {
                        showToast(searchResultBaseModel.message);
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }

            @Override
            public void onError() {
                mRefreshView.setRefreshing(false);
                showErrorNet();
            }
        });
    }

    private List<SearchWrapper> groupData(SearchResult data) {
        List<SearchWrapper> wrappers = new ArrayList<>();
        if (data.getUserList().size() != 0) {
            SearchWrapper titleWrapper = new SearchWrapper(SearchWrapper.HEADER);
            titleWrapper.setTitle("用户");
            wrappers.add(titleWrapper);
            for (SearchResult.UserListBean userListBean : data.getUserList()) {
                SearchWrapper searchWrapper = new SearchWrapper(SearchWrapper.USER);
                searchWrapper.setUserListBean(userListBean);
                wrappers.add(searchWrapper);
            }
        }
        if (data.getLetterList().size() != 0) {
            SearchWrapper titleWrapper = new SearchWrapper(SearchWrapper.HEADER);
            titleWrapper.setTitle("信件");
            wrappers.add(titleWrapper);
            for (SearchResult.LetterListBean letterListBean : data.getLetterList()) {
                SearchWrapper searchWrapper = new SearchWrapper(SearchWrapper.LETTER);
                searchWrapper.setLetterListBean(letterListBean);
                wrappers.add(searchWrapper);
            }
        }
        return wrappers;
    }

    private void showSuccess(List<SearchWrapper> letterList) {
        if (curPage == 1) {
            searchAdapter.setNewData(letterList);
            searchAdapter.setEmptyView(R.layout.view_default_emtpy, mRvList);
            searchAdapter.disableLoadMoreIfNotFullPage(mRvList);
        } else {
            int loadCount = letterList.size();
            searchAdapter.addData(letterList);
            if (loadCount < 8) {
                searchAdapter.loadMoreEnd();
            } else {
                searchAdapter.loadMoreComplete();
            }
        }
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        // TODO: add setContentView(...) invocation
        ButterKnife.bind(this);
    }

    @OnClick(R.id.btn_search)
    public void onViewClicked() {
        curPage = 1;
        fetchResult();
    }
}
